<?php

declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace Plugin\Attractions\Broadcast\Repository\Broadcast_plans;

use Plugin\Attractions\Broadcast\Model\Broadcast_plans\BroadcastPlans;
use Hyperf\Database\Model\Builder;
use App\Repository\IRepository;
use Hyperf\Collection\Arr;
use Plugin\Attractions\Broadcast\Constant;

/**
 * 广播计划配置 Repository类
 */
class BroadcastPlansRepository extends IRepository
{
    public function __construct(
        protected readonly BroadcastPlans $model
    ) {}

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {

        // 主键ID
        if (isset($params['id']) && !empty($params['id'])) {
            $query->where('id', '=', $params['id']);
        }

        // 计划名称
        if (isset($params['plan_name']) && !empty($params['plan_name'])) {
            $query->where('plan_name', 'like', '%' . $params['plan_name'] . '%');
        }

        // 计划描述
        if (isset($params['plan_description']) && !empty($params['plan_description'])) {
            $query->where('plan_description', '=', $params['plan_description']);
        }

        // 广播文字内容
        if (isset($params['content_text']) && !empty($params['content_text'])) {
            $query->where('content_text', '=', $params['content_text']);
        }

        // 音频文件路径
        if (isset($params['content_audio_file']) && !empty($params['content_audio_file'])) {
            $query->where('content_audio_file', '=', $params['content_audio_file']);
        }

        // 目标设备（JSON格式：设备ID数组）
        if (isset($params['target_devices']) && !empty($params['target_devices'])) {
            $query->where('target_devices', '=', $params['target_devices']);
        }

        // 目标分组（JSON格式：分组名称数组）
        if (isset($params['target_groups']) && !empty($params['target_groups'])) {
            $query->where('target_groups', '=', $params['target_groups']);
        }

        // 开始时间，控制播放时间段
        if (isset($params['start_time']) && !empty($params['start_time'])) {
            $query->where('start_time', '=', $params['start_time']);
        }

        // 结束时间，控制播放时间段
        if (isset($params['end_time']) && !empty($params['end_time'])) {
            $query->where('end_time', '=', $params['end_time']);
        }

        // 执行日期，逗号间隔，按不同重复类型
        if (isset($params['execution_day']) && !empty($params['execution_day']) && is_array($params['execution_day']) && count($params['execution_day']) == 2) {
            $query->whereBetween(
                'execution_day',
                [$params['execution_day'][0], $params['execution_day'][1]]
            );
        }

        // 重复类型：1-不重复，2-每天，3-每周，4-每月
        if (isset($params['repeat_type']) && !empty($params['repeat_type'])) {
            $query->whereIn('repeat_type', Arr::wrap($params['repeat_type']));
        }

        // 重复间隔（分钟）
        if (isset($params['repeat_interval']) && !empty($params['repeat_interval'])) {
            $query->where('repeat_interval', '=', $params['repeat_interval']);
        }

        // 重复次数
        if (isset($params['repeat_count']) && !empty($params['repeat_count'])) {
            $query->where('repeat_count', '=', $params['repeat_count']);
        }

        // 触发事件ID
        if (isset($params['trigger_event']) && !empty($params['trigger_event'])) {
            $query->where('trigger_event', '=', $params['trigger_event']);
        }

        // 触发条件（JSON格式）
        if (isset($params['trigger_condition']) && !empty($params['trigger_condition'])) {
            $query->where('trigger_condition', 'like', '%' . $params['trigger_condition'] . '%');
        }

        // 音量
        if (isset($params['volume_day']) && !empty($params['volume_day'])) {
            $query->where('volume_day', '=', $params['volume_day']);
        }

        // 计划状态：1-草稿，2-待执行，3-执行中，4-已取消
        if (isset($params['plan_status']) && !empty($params['plan_status'])) {
            $query->where('plan_status', '=', $params['plan_status']);
        }

        // 最后执行时间
        if (isset($params['last_execution_time']) && !empty($params['last_execution_time']) && is_array($params['last_execution_time']) && count($params['last_execution_time']) == 2) {
            $query->whereBetween(
                'last_execution_time',
                [$params['last_execution_time'][0], $params['last_execution_time'][1]]
            );
        }

        // 已执行次数
        if (isset($params['execution_count']) && !empty($params['execution_count'])) {
            $query->where('execution_count', '=', $params['execution_count']);
        }

        // 备注
        if (isset($params['remark']) && !empty($params['remark'])) {
            $query->where('remark', '=', $params['remark']);
        }

        return $query;
    }

    public function getPlayList(): array
    { 
        $time = date('H:i:s');
        return $this->model->query()
            ->where('plan_status', Constant::PLAN_STATUS_RUNNING)
            ->where('repeat_type', '!=', Constant::REPEAT_TYPE_NO)
            ->where('start_time', '<=', $time)
            ->where('end_time', '>', $time)
            ->get([
                'id', 'plan_name', 'content_text', 'content_audio_file', 'target_devices', 'target_groups',
                'execution_day', 'repeat_type', 'repeat_interval', 'repeat_count',
                'trigger_event', 'trigger_condition', 'volume_day', 'plan_status',  'last_execution_time'
            ])
            ->toArray();
    }

    public function initExecutionCount()
    {
        $this->getQuery()->update([
            'execution_count' => 0
        ]);
    }
}